﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using AdminModule.IndexMarkServiceReference;
using AdminModule.Views;
using InpValidator;
using AdminModule.StructEditStratagies;
using AdminModule.CommonClasses;
using System.Collections.ObjectModel;
using AdminModule.ViewModels;

namespace AdminModule.UserControls.StructView
{
    public partial class UniversityStruct : StructViewBase
    {
        private IndexMarkServiceClient client = new IndexMarkServiceClient();

        private bool _WithRespondents = true;
        public bool WithRespondents
        {
            get
            {
                return this._WithRespondents;
            }
            set
            {
                this._WithRespondents = value;
            }
        }

        public UniversityStruct()
        {
            InitializeComponent();
            this.viewModel = this.Resources["commonVM"] as CommonVM2;

            client.SaveUniversityStructCompleted += (s, ev) =>
                {
                    base.events.RaiseFreeEvent(FreeEvent.Save, s, ev);
                };
            client.CopyUniversityStructCompleted += (s, ev) =>
                {
                    base.events.RaiseFreeEvent(FreeEvent.Copy, s, ev);
                };
            client.CopyUniversityElementCompleted += (s, ev) =>
                {
                    base.events.RaiseFreeEvent(FreeEvent.Copy, s, ev);
                };
            client.GetUniversityStructOnDemandCompleted += (s, ev) =>
                {
                    (TreeView.SelectedItem as DTOChilds).Childs.LoadFrom(ev.Result);
                    base.events.RaiseFreeEvent(FreeEvent.LoadData, s, ev);
                };
        }

        public override void Init(int IDTerm)
        {
            base.Init(IDTerm);
            this.viewModel.Init(StructName.University, IDTerm);
            this.structEditStrategy = new UniversityStructEditStrategy(IDTerm);
            this.SetBinding(this.viewModel, "UniversityStructRoots");
            this.SetTemplate(Resources["DepartmentRootLevel"] as DataTemplate);
        }

        public override void LoadData()
        {
            this.viewModel.LoadUniversityStruct(IDTerm, WithRespondents, base.isLoadOnDemand);
        }

        public override void LoadOnDemand(TreeViewItem treeViewItem, DTOBase obj)
        {
            if (obj is AdmDepartment)
            {
                base.events.RaiseBusyEvent(BusyEvent.LoadData);
                client.GetUniversityStructOnDemandAsync(IDTerm, obj as AdmDepartment, WithRespondents);
            }
        }

        private void jobComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBox comboBox = sender as ComboBox;
            if (comboBox.SelectedItem == null) return;
            AdmRespondent respondent = comboBox.Tag as AdmRespondent;
            respondent.Job = comboBox.SelectedItem as AdmJob;
        }

        private void jobComboBox_Loaded(object sender, RoutedEventArgs e)
        {
            ComboBox comboBox = sender as ComboBox;
            if (comboBox.SelectedItem != null) return;
            AdmRespondent respondent = comboBox.Tag as AdmRespondent;
            // Если это только что добавленный сотрудник, то у него может отсутствовать должность
            if (respondent.Job == null) return;
            comboBox.SelectedItem = viewModel.AdmJobCollection.First(f => f.IDJob == respondent.Job.IDJob);
        }

        public override List<TypeInfo> GetTypesList()
        {
            List<TypeInfo> typesList = new List<TypeInfo>();
            typesList.Add(new TypeInfo
                {
                    Name = "Отделы",
                    window = new SelectAddItemsWindow(EnumSelectObjects.AdmDepartment),
                    forParentTypesAdd = new List<Type> { typeof(RootTreeView), typeof(AdmDepartment) },
                    forParentTypesReplace = new List<Type> { typeof(AdmDepartment) }
                });
            typesList.Add(new TypeInfo 
                {
                    Name = "Сотрудников",
                    window = new SelectAddItemsWindow(EnumSelectObjects.AdmPerson),
                    forParentTypesAdd = new List<Type> { typeof(AdmDepartment) },
                    forParentTypesReplace = new List<Type> { typeof(AdmRespondent) }
                });
            return typesList;
        }

        public override void Save()
        {
            base.events.RaiseBusyEvent(BusyEvent.Save);
            client.SaveUniversityStructAsync(StructViewBase.changedElements);
        }

        public override void CopyAll(int fromIDTerm, int toIDTerm)
        {
            base.events.RaiseBusyEvent(BusyEvent.Copy);
            client.CopyUniversityStructAsync(fromIDTerm, toIDTerm);
        }

        public override void CopySelected(DTOBase targetObject, int toIDTerm)
        {
            base.events.RaiseBusyEvent(BusyEvent.Copy);
            client.CopyUniversityElementAsync(CurrentItem.selectedItem, toIDTerm, 
                (targetObject is RootTreeView) ? null : targetObject);
        }

        private void rootNode_Loaded(object sender, RoutedEventArgs e)
        {
            this.TreeView.ExpandToDepth(1);
        }

        private void InitValidator(object sender, RoutedEventArgs e)
        {
            ValidatorBase v = sender as ValidatorBase;
            v.SetEnvironment(LayoutRoot, MainManager);
        }
    }
}
